package com.ling.sdk.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import com.alibaba.android.arouter.launcher.ARouter
import com.ling.sdk.live.ILiveUI
import com.ling.sdk.live.ILiveUIChild
import com.ling.sdk.live.ILiveUIParent
import com.ling.sdk.live.LiveManager
import me.yokeyword.fragmentation.SupportFragment

abstract class BaseFragment : SupportFragment(), ILiveUI, ILiveUIParent, ILiveUIChild, IInit {


    var titleView: ITitle? = null
        set(value) {
            field = value; setUpTitleView()
        }
    var stateView: IStateView? = null
        set(value) {
            field = value;setUpStateView()
        }


    private val titleViewParent = lazy { LinearLayout(contentRootView.context).apply { orientation = LinearLayout.VERTICAL } }
    private val stateViewParent = lazy { FrameLayout(contentRootView.context) }

    lateinit var contentRootView: View
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        contentRootView = inflater.inflate(getLayoutId(), container, false)
        // 这里仅给toolbar设置标题，返回箭头等轻量UI的操作
        onInitTitleState()
        return setContentView(contentRootView)
    }


    abstract fun getLayoutId(): Int

    override fun onLazyInitView(savedInstanceState: Bundle?) {
        // 这里设置Listener、各种Adapter、请求数据等等

    }

    override fun onInitView() {}
    override fun onInitData() {}
    override fun onInitListener() {}
    override fun onInitTitleState() {}

    private fun setContentView(view: View): View {
        titleViewParent.value.addView(view)
        return titleViewParent.value

    }

    private fun setUpTitleView() {
        titleView?.getView()?.addToParent(titleViewParent.value, 0, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
    }

    private fun setUpStateView() {

        if (!stateViewParent.isInitialized()) {
            //如果状态父布局没有被初始化

            contentRootView.addToParent(stateViewParent.value)

            stateViewParent.value.addToParent(titleViewParent.value)
        }
        stateView?.getLoadingView()?.addToParent(stateViewParent.value)
        stateView?.getEmptyView()?.addToParent(stateViewParent.value)
    }

    private fun View.addToParent(viewGroup: ViewGroup?, index: Int = -1, params: ViewGroup.LayoutParams? = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) {
        viewGroup?.also {
            if (this.parent == null) {
                if (index == -1) it.addView(this, params)
                else it.addView(this, index, params)
            }
        }
    }

    fun getRootView() = if (contentRootView is ViewGroup) contentRootView as ViewGroup else contentRootView.parent as ViewGroup

    private val pendingAttachTask = ArrayList<Runnable>()

    override fun onAttach(activity: Activity) {
        super.onAttach(activity)
        LiveManager.addLiveUI(activity, this)
        pendingAttachTask.forEach { it.run() }
        pendingAttachTask.clear()

    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        onInitView()
        onInitListener()
        onInitData()
    }

    override fun add(live: ILiveUI?) {
        if (activity != null) LiveManager.addLiveUI(activity, live)
        else
            pendingAttachTask.add(Runnable { LiveManager.addLiveUI(activity, live) })
    }

    override fun remove(live: ILiveUI?) {
        LiveManager.removeLiveUI(activity, live)
    }

    var token = this.toString()

    override fun onAttachLive(token: String) {
        this.token = token
    }

    open fun showLoad(isFinished: Boolean) {
        if (isFinished) stateView?.hideLoading()
        else
            stateView?.showLoading()
    }

    open fun showEmpty(visibility: Boolean) {
        if (visibility) stateView?.hideEmpty()
        else
            stateView?.showEmpty()
    }

    open fun showState(state: Int) {
        stateView?.showState(state)
    }

    override fun getContext() = LiveManager.getContext(token)

    override fun handler() = LiveManager.handler(context)

    override fun getLiveToken() = token

    override fun onActivityFinish() {}

    override fun onActivityPause() {}

    override fun onActivityResume() {}

    override fun onActivityStop() {}

    override fun receiverMessage(any: Any) = false

    override fun onNetworkChange(isConnected: Boolean, netType: Int) {}

    override fun sendMessage(data: Any) {
        LiveManager.sendMessage(this,context, data)
    }

    override fun sendMessageAsync(data: Any) {
        LiveManager.sendMessage(this,context, data)
    }

    override fun onUIActivityOnResult(requestCode: Int, result: Int, data: Intent?) {}


    override fun onBackPressedSupport(): Boolean {
        return super.onBackPressedSupport()
    }

    override fun onCleanUp() {}

}